using dotnet_ef_admin.Src.Models;
using dotnet_ef_admin.Src.Services;
using Microsoft.AspNetCore.Mvc;

namespace dotnet_ef_admin.Src.Controllers;

/// <summary>
/// 菜单控制器，处理菜单相关的HTTP请求。
/// </summary>
[Route("/api/v1/[controller]")]
[ApiController]
public class MenuController(IMenuService _menuService) : ControllerBase {
    /// <summary>
    /// 获取所有菜单。
    /// </summary>
    /// <returns>返回所有菜单的列表。</returns>
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Menu>>> GetMenus([FromQuery] FindAllDictTypesDto dto) {
        var menus = await _menuService.GetAllMenusAsync(dto);
        return Ok(menus);
    }

    /// <summary>
    /// 根据ID获取菜单。
    /// </summary>
    /// <param name="id">菜单ID。</param>
    /// <returns>返回与ID匹配的菜单。</returns>
    [HttpGet("{id}/form")]
    public async Task<ActionResult<MenuNodeResult>> GetMenu(int id) {
        var menu = await _menuService.GetMenuByIdAsync(id);
        if (menu == null) return NotFound();
        return Ok(menu);
    }

    /// <summary>
    /// 创建新菜单。
    /// </summary>
    /// <param name="menu">菜单对象。</param>
    /// <returns>返回创建的菜单对象。</returns>
    [HttpPost]
    public async Task<ActionResult<MenuNodeResult>> PostMenu(MneuNodeRequest menu) {
        var newMenu = await _menuService.CreateMenuAsync(menu);
        return Ok(newMenu);
    }

    /// <summary>
    /// 更新菜单。
    /// </summary>
    /// <param name="id">菜单ID。</param>
    /// <param name="menu">菜单对象。</param>
    /// <returns>返回更新后的菜单对象。</returns>
    [HttpPut("{id}")]
    public async Task<ActionResult<MenuNodeResult>> PutMenu(int id, MenuNodeResult menu) {
        if (id != menu.Id) return BadRequest();

        var updatedMenu = await _menuService.UpdateMenuAsync(menu);
        return Ok(updatedMenu);
    }

    /// <summary>
    /// 删除菜单。
    /// </summary>
    /// <param name="id">菜单ID。</param>
    /// <returns>删除操作结果。</returns>
    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteMenu(int id) {
        await _menuService.DeleteMenuAsync(id);
        return Ok("Deleted");
    }

    [HttpGet("routes")]
    public async Task<IActionResult> GetRoutes() {
        var menuList = await _menuService.GetListRoutes();
        return Ok(menuList);
    }
}
